package com.bgdCA.controller;

import com.bgdCA.domain.Account;
import com.bgdCA.response.CodeMsg;
import com.bgdCA.response.Result;
import com.bgdCA.service.IMailService;
import com.bgdCA.service.ResetPsdService;
import com.bgdCA.service.impl.CaptchaNoPicture;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.concurrent.TimeUnit;

@Controller
@Slf4j
public class ResetPsdController {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    IMailService mailService;

    @Autowired
    ResetPsdService resetPsdService;

    @Autowired
    CaptchaNoPicture captchaNoPicture;

    @Transactional(propagation = Propagation.REQUIRED, rollbackForClassName = "Exception")
    @RequestMapping("/reset")
    @ResponseBody
    public Result reset(@RequestBody Account account) {

        String username = account.getUsername();
        String mail = account.getMail();

        //查找用户
        Account account1 = resetPsdService.findUser(username);
        log.debug(account1.getMail());

        //判断用户是否为空
        if (account1 == null) {
            return Result.error(CodeMsg.RESET_USER_NOT_FOUND);
        }
        //判断邮箱是否正确
        if (!mail.equals(account1.getMail())) {
            return Result.error(CodeMsg.RESET_MAIL_NOT_RIGHT);
        }

        String captcha = captchaNoPicture.CreatCaptcha();

        String[] to = {mail};

        String key = username;
        redisTemplate.opsForValue().set(key, captcha);

        redisTemplate.expire(key, 1, TimeUnit.DAYS);

        mailService.resetTemplateMail(to, "reset", captcha);

        return Result.success(null);
    }

}
